<template>
  <div>
    <div
        style="width: 1670px;min-height:770px;padding:24px 32px;margin:15px 0 15px 35px;
        border-radius: 26px;background-color: white">
      <div v-if="taskShow" style="width: 800px">
        <p style="margin: 0;font-size: 18px">测验与作业</p>
        <el-collapse v-model="activeNames" @change="handleChange" style="margin-top: 20px">
          <el-collapse-item v-for="(item,index) in chapterList" :title="item.chapterName" :name="index">
            <div v-for="(it,ind) in taskList" v-if="it.chapterId===item.chapterId"
                 style="margin: 20px 0 30px 30px" :id="'task'+index+'-'+ind">
              <div style="display: flex;height: 32px">
                <el-link :href="'/#/learnEdit/testListEdit/'+item.courseId+'/'+item.chapterId+'/'+it.taskId"
                         style="font-size: 16px;" :underline="false">
                  <div style="display: flex;height: 32px;width: 660px;padding-top: 8px">
                    <a v-if="it.content" class="el-icon-circle-check" style="border-radius: 50%;
                background-color: #409EFF;color: white;font-size: 24px;height: 24px;width: 24px"></a>
                    <a v-else class="el-icon-remove-outline" style="font-size: 24px;"></a>
                    <div style="margin: 4px 0 0 8px">{{ it.taskName }}</div>
                  </div>
                </el-link>
                <el-button type="primary" size="small" style="height: 32px;margin-bottom: 8px" :key="it.taskId"
                           icon="el-icon-edit" @click="onScoring(it.chapterId,it.taskId)" circle></el-button>
                <el-button type="danger" size="small" style="height: 32px;margin:0 0 8px 12px" :key="it.taskId"
                           icon="el-icon-delete" @click="openDeleteTask(it.taskId)" circle></el-button>
              </div>
            </div>
            <div style="height: 60px;white-space:nowrap;">
              <el-button class="el-icon-plus" type="primary" :key="'add-'+index" @click="onAddTask(item.chapterId)"
                         style="margin:10px 0 10px 30px">添加作业
              </el-button>
            </div>
          </el-collapse-item>
        </el-collapse>
        <el-dialog
            :visible.sync="addVisible"
            width="30%"
            top="300px"
            center>
          <el-form :model="addTask" :rules="rules" ref="addTaskFrom"
                   style="width: 70%;margin-left: 75px">
            <p style="text-align: center;width: 100%;font-size: 20px">新增作业</p>
            <el-form-item prop="taskName">
              <el-input v-model="addTask.taskName" placeholder="请输入作业名"
                        style="width: 350px;height: 46px;margin:10px 0">
              </el-input>
            </el-form-item>
            <el-form-item style="text-align: center">
              <el-button type="primary" style="width: 300px" @click="addTaskRun(courseId,chapterId)">确 定</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
      <div v-if="!taskShow">
        <p style="margin: 0;font-size: 18px">
          <el-form style="display: flex">
            <a style="margin-top: 6px">测验与作业</a>
            <i class="el-icon-arrow-right" style="margin: 10px"></i>
            <el-form-item style="width: 150px">
              <el-select v-model="chapterId" placeholder="请选择章节">
                <el-option @click.native="onClickChapter" v-for="(item,index) in chapterList"
                           :key="item.chapterId" :label="item.chapterName" :value="item.chapterId"></el-option>
              </el-select>
            </el-form-item>
            <i class="el-icon-arrow-right" style="margin: 10px"></i>
            <el-form-item style="width: 150px">
              <el-select v-model="taskId" placeholder="请选择作业">
                <el-option @click.native="onClickTask()" v-for="(item,index) in taskList"
                           v-if="item.chapterId===chapterId"
                           :key="item.taskId" :label="item.taskName" :value="item.taskId"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </p>
        <el-form :model="task" :rules="rules" label-width="30px"
                 style="display: flex;flex-direction: column;width: 800px" ref="taskForm">
          <p style="font-size: 18px;margin-left: 30px">作业名</p>
          <el-form-item prop="taskName">
            <el-input v-model="task.taskName" placeholder="请输入作业名"></el-input>
          </el-form-item>
          <p style="font-size: 18px;margin-left: 30px">作业分数</p>
          <el-form-item prop="score">
            <el-input-number v-model="task.score" :precision="2" :step="0.1" :max="10"></el-input-number>
          </el-form-item>
          <p style="font-size: 18px;margin-left: 30px">作业限制提交次数</p>
          <el-form-item prop="submitnum">
            <el-input-number v-model="task.submitnum"></el-input-number>
          </el-form-item>
          <p style="font-size: 18px;margin-left: 30px">作业内容</p>
          <el-form-item prop="content">
            <div id="div1">
            </div>
          </el-form-item>
          <p style="font-size: 18px;margin-left: 30px">作业答案</p>
          <el-form-item prop="answer">
            <div id="div2">
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addOrUpdate('taskForm')">提 交</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import E from 'wangeditor'

export default {
  name: "TestListEditView",
  data() {
    return {
      activeNames: ['1'],
      courseId: '',
      chapterId: '',
      taskId: '',
      task: '',
      chapterList: [],
      taskList: [],
      taskShow: false,
      addVisible: false,
      addTask: {taskName: ''},
      isChange1: false,
      isChange2: false,
      rules: {
        content: {required: true, message: '作业内容不能为空', trigger: 'blur'},
        taskName: {required: true, message: '作业名不能为空', trigger: 'blur'},
        // answer:{required: true, message: '作业内容不能为空', trigger: 'blur'}
      }
    }
  },
  watch: {
    task(val) {
      if (!this.isChange1) {
        this.editor1.txt.html(this.task.content);
        this.editor2.txt.html(this.task.answer);
      }
      this.isChange1 = false;
      this.isChange2 = false;
    }
  },
  methods: {
    onAddTask(chapterId) {
      if (this.$refs.addTaskFrom !== undefined) {
        this.$nextTick(() => {
          this.$refs.addTaskFrom.resetFields();
        });
      }
      this.chapterId = chapterId;
      this.addVisible = true;
    },
    addTaskRun(courseId, chapterId) {
      this.$refs.addTaskFrom.validate((valid) => {
        if (valid) {
          this.$axios({
            method: 'post',
            url: "http://localhost:8089/task/createTask",
            data: {"taskName": this.addTask.taskName, "courseId": courseId, "chapterId": chapterId}
          }).then(res => {
            if (res.data.code === 200) {
              this.$message.success("添加作业成功");
              this.getTaskByCourseId(courseId);
              this.addVisible = false;
            } else
              this.$message.error(res.data.msg)
          }).catch(err => console.log(err));
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    openDeleteTask(taskId) {
      this.$confirm('此操作将永久删除该作业, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteTask(taskId);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    deleteTask(taskId) {
      this.$axios({
        method: 'get',
        url: `http://localhost:8089/task/deleteTask/${taskId}`
      }).then(res => {
        if (res.data.code === 200) {
          this.$message.success(res.data.msg);
          this.getTaskByCourseId(this.courseId);
        } else
          this.$message.error(res.data.msg);
      }).catch(err => console.log(err));
    },
    getChapterByCourseId(courseId) {
      this.$axios({
        method: 'get',
        url: `http://localhost:8089/chapter/selectChapterByCourseId/${courseId}`
      }).then(res => {
        if (res.data.code === 200)
          this.chapterList = res.data.dataobject;
      }).catch(err => console.log(err));
    },
    getTaskByCourseId(courseId) {
      this.$axios({
        method: 'get',
        url: `http://localhost:8089/user/task/selectTaskByCourseId/${courseId}`
      }).then(res => {
        if (res.data.code === 200)
          this.taskList = res.data.dataobject;
      }).catch(err => console.log(err));
    },
    getTaskByTaskId(taskId) {
      this.$axios({
        method: 'get',
        url: `http://localhost:8089/task/selectTaskById/${taskId}`
      }).then(res => {
        if (res.data.code === 200)
          this.task = res.data.dataobject;
      }).catch(err => console.log(err));
    },
    updateTask(task) {
      this.$axios({
        method: 'post',
        url: "http://localhost:8089/task/updateTask",
        data: {
          'taskId': task.taskId, "taskName": task.taskName, "dealine": task.dealine,
          "score": task.score, "submitnum": task.submitnum, "content": task.content, "answer": task.answer
        }
      }).then(res => {
        if (res.data.code === 200)
          this.$message.success("修改作业成功")
        else
          this.$message.error("修改作业失败")
      }).catch(err => console.log(err));
    },
    //创建富文本编辑器，并进行上传图片、上传视颜的配置
    createRichTextEditor() {
      this.editor1 = new E('#div1');
      this.editor1.config.uploadImgServer = 'http://localhost:8089/richText/uploadFile?type=img';
      this.editor1.config.uploadFileName = 'file';
      this.editor1.config.uploadVideoServer = 'http://localhost:8089/richText/uploadFile?type=video';
      this.editor1.config.uploadVideoName = 'file';
      this.editor1.config.placeholder = '请在此处填写作业内容';
      this.editor1.config.zIndex = 500
      this.editor1.config.onchange = (html) => {
        this.isChange1 = true;
        this.task.content = html//绑定当前逐渐地值
      }
      this.editor1.create();
      this.editor2 = new E('#div2');
      this.editor2.config.uploadImgServer = 'http://localhost:8089/richText/uploadFile?type=img';
      this.editor2.config.uploadFileName = 'file';
      this.editor2.config.uploadVideoServer = 'http://localhost:8089/richText/uploadFile?type=video';
      this.editor2.config.uploadVideoName = 'file';
      this.editor2.config.placeholder = '请在此处填写作业答案';
      this.editor2.config.zIndex = 500
      this.editor2.config.onchange = (html) => {
        this.isChange2 = true;
        this.task.answer = html//绑定当前逐渐地值
      }
      this.editor2.create();
    },
    //确定按钮
    addOrUpdate(formName) {
      // this.task.content=this.editor1.txt.html();
      // this.task.answer=this.editor2.txt.html();
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.updateTask(this.task);
          setTimeout(() => this.getTaskByCourseId(this.courseId), 300)
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    handleChange(val) {
      console.log(val);
    },
    onClickChapter() {
      this.taskId = '';
    },
    onClickTask() {
      this.$router.push({
        path: '/learnEdit/testListEdit/' + this.courseId + '/' + this.chapterId + '/' + this.taskId
      }).catch(err => console.log(err));
    },
    onScoring(chapterId, taskId) {
      this.$router.push({
        path: '/learnEdit/testScoring/' + this.courseId + '/' + chapterId + '/' + taskId
      }).catch(err => console.log(err));
    }
  },
  created() {
    this.courseId = parseInt(this.$route.params.courseId);
    this.chapterId = parseInt(this.$route.params.chapterId);
    this.taskId = parseInt(this.$route.params.taskId);
    this.task = {content: ''}
    this.getChapterByCourseId(this.courseId);
    this.getTaskByCourseId(this.courseId);
    if (!this.chapterId)
      this.taskShow = true;
    else {
      this.getTaskByTaskId(this.taskId);
      this.$nextTick(() => {
        if (!this.editor1) {
          this.createRichTextEditor();
        }
      });
    }
  },
}
</script>

<style scoped>
/deep/ .el-collapse-item__header {
  color: #333333;
  font-size: 16px;
  margin-top: 15px;
  border-radius: 10px;
  padding: 5px 20px;
  background-color: #F7F7F7 !important;
  position: relative;
}

/deep/ .el-collapse-item__content {
  text-align: left;
//color: #fff ; //background-color: #313743; padding-bottom: 0;

  div {
    height: .96rem;
    line-height: .96rem;
  }
}
</style>